<template>
  <div
      class="smart-navbar"
      :style="{
      transform: `translateY(${currentTranslateY}px)`,
      transition: `transform ${transitionTime}ms ease-out`
    }"
  >
    <slot />
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted, computed} from 'vue'
import emitter from "@/utils/emitter.js";
import {useRoute} from "vue-router";

const props = defineProps({
  // 触发完全隐藏的滚动距离（默认 100px）
  hideThreshold: {
    type: Number,
    default: 100
  },
  // 触发重新显示的滚动距离（默认 200px）
  showThreshold: {
    type: Number,
    default: 200
  },
  // 过渡时间（毫秒）
  transitionTime: {
    type: Number,
    default: 300
  }
})
const textColor = ref('#000') // 默认黑色

const currentScrollY = ref(0)
const lastScrollY = ref(0)
const currentTranslateY = ref(0)
// 新增计算是否在第三阶段
const isStageThree = computed(() => currentScrollY.value >= props.showThreshold)

// 优化滚动处理
const handleScroll = () => {
  currentScrollY.value = window.scrollY || document.documentElement.scrollTop

  // 计算滚动方向
  const scrollDirection = currentScrollY.value > lastScrollY.value ? 'down' : 'up'

  // 第一阶段：随滚动下移渐隐
  if (currentScrollY.value <= props.hideThreshold) {
    currentTranslateY.value = -currentScrollY.value * 0.5
  }
  // 第二阶段：完全隐藏
  else if (currentScrollY.value > props.hideThreshold && currentScrollY.value < props.showThreshold) {
    currentTranslateY.value = -props.hideThreshold * 0.5
  }
  // 第三阶段：超过显示阈值后重新出现
  else {
    currentTranslateY.value = 0
    //
  }

  // 新增颜色变化逻辑
  if (isStageThree.value) {
    // textColor.value = '#000' // 进入第三阶段变白色
    emitter.emit("changeBgColor", {color:"black", hasColor:true})
    // emitter.emit("test01","aaa","true");
  } else {
    // textColor.value = '#fff' // 其他阶段恢复黑色
    // emitter.emit("changeBgColor","white",true)
    if(route.path === '/'){
      // emitter.emit("changeBgColor",{color:"#7122ff", hasColor:false})
      emitter.emit("changeBgColor",{color:"white", hasColor:false})
    }
  }
  lastScrollY.value = currentScrollY.value
}

const route = useRoute()
// 节流函数
const throttle = (fn, wait = 100) => {
  let lastTime = 0
  return (...args) => {
    const now = Date.now()
    if (now - lastTime >= wait) {
      fn.apply(this, args)
      lastTime = now
    }
  }
}

// 事件监听
const throttledScroll = throttle(handleScroll, 50)

onMounted(() => {
  window.addEventListener('scroll', throttledScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', throttledScroll)
})
</script>

<style scoped>
.smart-navbar {
  color: #d1faff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
  will-change: transform;
  transition:
      transform v-bind('props.transitionTime + "ms"') ease-out,
      color v-bind('props.transitionTime + "ms"') ease-out;
  //background: #fff; /* 可根据需要修改 */
  //box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>